<script setup>
import { onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { User, Plus } from '@element-plus/icons-vue';

// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '小明',
    qualification: '国家二级心理咨询师',
    organization: '心理健康中心',
    addTime: '2023-10-27 10:00:00',
    editTime: '',
    personalProfile: '经验丰富，擅长处理各种心理问题。',
    trainingBackground: '毕业于北京师范大学心理学专业。',
    avatar: ''
  },
])

// 资质选项
const qualificationOptions = [
    '国家一级咨询师', '国家二级咨询师', '国家三级咨询师', '心里治疗师', 
    '注册助理心理咨询师', '注册心理咨询师', '注册督导师', '其他'
];

// 表格数据的复制品
const tableDataCopy = ref([])
// 当前页数据
const currentTableData = ref([])
// 当前页
const currentPage = ref(1)
// 当前页大小
const currentPageSize = ref(10)
// 搜索信息
const searchInfo = ref({ name: '' })

// 对话框
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const editingCounselor = ref(null)

// 表单
const addFormRef = ref(null);
const editFormRef = ref(null);

const addForm = ref({
    name: '',
    qualification: '',
    organization: '',
    personalProfile: '',
    trainingBackground: '',
    avatar: ''
});

const editForm = ref({
    name: '',
    qualification: '',
    organization: '',
    personalProfile: '',
    trainingBackground: '',
    avatar: ''
});

// 验证规则
const rules = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    qualification: [{ required: true, message: '请选择资质', trigger: 'change' }],
    organization: [{ required: true, message: '请输入一级组织结构', trigger: 'blur' }],
    personalProfile: [{ required: true, message: '请输入个人简介', trigger: 'blur' }],
    trainingBackground: [{ required: true, message: '请输入受训背景', trigger: 'blur' }]
};


// 页大小改变
const handleSizeChange = (newPageSize) => {
  currentPageSize.value = newPageSize;
  updateCurrentTableData();
}
// 改变页
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  updateCurrentTableData();
}

const updateCurrentTableData = () => {
    const start = (currentPage.value - 1) * currentPageSize.value
    const end = start + currentPageSize.value
    currentTableData.value = tableData.value.slice(start, end)
}

// 搜索
const search = () => {
    if (!searchInfo.value.name) {
        tableData.value = [...tableDataCopy.value];
    } else {
        tableData.value = tableDataCopy.value.filter(item => item.name.includes(searchInfo.value.name));
    }
    currentPage.value = 1;
    updateCurrentTableData();
}
// 重置
const reset = () => {
  searchInfo.value = { name: '' }
  tableData.value = [...tableDataCopy.value];
  currentPage.value = 1;
  updateCurrentTableData();
}

// 从sessionStorage加载数据
const loadDataFromSession = () => {
    const data = sessionStorage.getItem('counselorData');
    if (data) {
        tableData.value = JSON.parse(data);
    } else {
        // 默认数据
        tableData.value = [
            {
                id: 1,
                name: '咨询师1',
                qualification: '国家二级心理咨询师',
                organization: '心理健康中心',
                addTime: '2023-10-27 10:00:00',
                editTime: '',
                personalProfile: '经验丰富，擅长处理各种心理问题。',
                trainingBackground: '毕业于北京师范大学心理学专业。',
                avatar: ''
            },
        ];
    }
};

// 保存数据到sessionStorage
const saveDataToSession = () => {
    sessionStorage.setItem('counselorData', JSON.stringify(tableData.value));
};

// 添加操作
const handleAdd = () => {
    addForm.value = {
        name: '',
        qualification: '',
        organization: '',
        personalProfile: '',
        trainingBackground: '',
        avatar: ''
    };
    addDialogVisible.value = true;
}

// 保存添加
const saveAdd = async () => {
    if (!addFormRef.value) return;
    await addFormRef.value.validate((valid) => {
        if (valid) {
            const newCounselor = {
                id: Date.now(),
                ...addForm.value,
                addTime: new Date().toLocaleString(),
                editTime: ''
            };
            tableData.value.unshift(newCounselor);
            tableDataCopy.value = [...tableData.value];
            updateCurrentTableData();
            saveDataToSession(); // 保存到sessionStorage
            ElMessage({
                type: 'success',
                message: '添加成功',
            });
            addDialogVisible.value = false;
        }
    });
}

// 删除操作
const handleDelete = (index, row) => {
    ElMessageBox.confirm(
        `确定要删除咨询师 "${row.name}" 吗?`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        const globalIndex = tableData.value.findIndex(item => item.id === row.id);
        if (globalIndex !== -1) {
            tableData.value.splice(globalIndex, 1);
            tableDataCopy.value = [...tableData.value];
            updateCurrentTableData();
            saveDataToSession(); // 保存到sessionStorage
            ElMessage({
                type: 'success',
                message: '删除成功',
            });
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除',
        });
    });
}

// 编辑操作
const handleEdit = (index, row) => {
    editingCounselor.value = row;
    editForm.value = { ...row };
    editDialogVisible.value = true;
}

// 保存编辑
const saveEdit = async () => {
    if (!editFormRef.value) return;
    await editFormRef.value.validate((valid) => {
        if (valid) {
            const index = tableData.value.findIndex(item => item.id === editingCounselor.value.id);
            if (index !== -1) {
                tableData.value[index] = { 
                    ...tableData.value[index], 
                    ...editForm.value, 
                    editTime: new Date().toLocaleString() 
                };
                tableDataCopy.value = [...tableData.value];
                updateCurrentTableData();
                saveDataToSession(); // 保存到sessionStorage
                ElMessage({
                    type: 'success',
                    message: '编辑成功',
                });
            }
            editDialogVisible.value = false;
        }
    });
}

// 图片上传
const handleAvatarChange = (uploadFile) => {
  const isJPGorPNG = uploadFile.raw.type === 'image/jpeg' || uploadFile.raw.type === 'image/png';
  const isLt2M = uploadFile.raw.size / 1024 / 1024 < 2;

  if (!isJPGorPNG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
    return;
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
    return;
  }

  // 将图片转换为Base64
  const reader = new FileReader();
  reader.readAsDataURL(uploadFile.raw);
  reader.onload = () => {
      if (addDialogVisible.value) {
        addForm.value.avatar = reader.result;
      } else {
        editForm.value.avatar = reader.result;
      }
  };
};


onMounted(() => {
  loadDataFromSession(); // 从sessionStorage加载数据
  // Make a copy for searching and resetting
  tableDataCopy.value = [...tableData.value];
  updateCurrentTableData();
})
</script>

<template>
<!-- 搜索部分 -->
<div class="search-box">
    <el-row>
        <el-col :span="9">
            <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>&nbsp;添加咨询师</el-button>
        </el-col>
        <el-col :span="5">
            <el-input v-model.trim="searchInfo.name" style="width: 240px" placeholder="请输入咨询师姓名" />
        </el-col>
        <el-col :span="3">
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
        </el-col>
    </el-row>
</div>
<!-- 表格部分 -->
<div class="table-box">
    <el-table :data="currentTableData" style="width: 100%" height="450px" :header-cell-style="{ 'background-color': '#f5f7fa' }">
        <el-table-column fixed prop="name" label="姓名" width="150" />
        <el-table-column prop="qualification" label="资质" width="200" />
        <el-table-column label="头像" width="100">
            <template #default="scope">
                <el-avatar :size="40" :src="scope.row.avatar">
                    <el-icon><User /></el-icon>
                </el-avatar>
            </template>
        </el-table-column>
        <el-table-column prop="organization" label="一级组织结构" width="200" />
        <el-table-column prop="addTime" label="添加时间" width="180" />
        <el-table-column prop="editTime" label="编辑时间" width="180" />
        <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button link type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
</div>

<!-- 添加对话框 -->
<el-dialog v-model="addDialogVisible" title="添加咨询师" width="40%">
    <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="120px">
        <el-form-item label="姓名" prop="name">
            <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="资质" prop="qualification">
            <el-select v-model="addForm.qualification" placeholder="请选择资质">
                <el-option v-for="item in qualificationOptions" :key="item" :label="item" :value="item" />
            </el-select>
        </el-form-item>
        <el-form-item label="一级组织结构" prop="organization">
            <el-input v-model="addForm.organization" />
        </el-form-item>
        <el-form-item label="个人简介" prop="personalProfile">
            <el-input type="textarea" v-model="addForm.personalProfile" />
        </el-form-item>
        <el-form-item label="受训背景" prop="trainingBackground">
            <el-input type="textarea" v-model="addForm.trainingBackground" />
        </el-form-item>
        <el-form-item label="头像">
            <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleAvatarChange">
                <img v-if="addForm.avatar" :src="addForm.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
        </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveAdd">保存</el-button>
        </span>
    </template>
</el-dialog>

<!-- 编辑对话框 -->
<el-dialog v-model="editDialogVisible" title="编辑咨询师" width="40%">
    <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="120px">
        <el-form-item label="姓名" prop="name">
            <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="资质" prop="qualification">
            <el-select v-model="editForm.qualification" placeholder="请选择资质">
                <el-option v-for="item in qualificationOptions" :key="item" :label="item" :value="item" />
            </el-select>
        </el-form-item>
        <el-form-item label="一级组织结构" prop="organization">
            <el-input v-model="editForm.organization" />
        </el-form-item>
        <el-form-item label="个人简介" prop="personalProfile">
            <el-input type="textarea" v-model="editForm.personalProfile" />
        </el-form-item>
        <el-form-item label="受训背景" prop="trainingBackground">
            <el-input type="textarea" v-model="editForm.trainingBackground" />
        </el-form-item>
        <el-form-item label="头像">
            <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleAvatarChange">
                <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
        </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveEdit">保存</el-button>
        </span>
    </template>
</el-dialog>

<!-- 分页部分 -->
<div class="page-box">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="currentPageSize"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
</div>
</template>

<style scoped>
.search-box {
    padding: 10px 0px 10px 10px;
}
.table-box {
    padding-left: 10px;
}
.page-box {
    display: flex;
    justify-content: center;
    padding-top: 10px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>